import axios from 'axios'
import ElementUI from 'element-ui';
import router from './router'
import store from './store'

//定义baseURL，因此每次向后端请求是，都在在前面加上baseURL
axios.defaults.baseURL = "http://localhost:8081"

//前置拦截
axios.interceptors.request.use(config => {
    return config
})

//后置拦截

axios.interceptors.response.use(
    response => {
        let res = response.data;

        console.log("=====================")
        console.log(res)
        console.log("=====================")

        if(res.code === 200){
            return response
        }else{
            ElementUI.Message({
                showClose: true,
                duration:2*1000,
                message: '错了哦，这是一条错误消息',
                type: 'error'
            });
            console.log(res.msg)
            return Promise.reject(res.msg)
        }
    },
    error => {
        console.log('err' + error)// for debug
        if(error.response.data) {
          error.message = error.response.data.msg
        }
        // 根据请求状态觉得是否登录或者提示其他
        if (error.response.status === 401) {
          store.commit('REMOVE_INFO');
          router.push({
            path: '/login'
          });
          error.message = '请重新登录';
        }
        if (error.response.status === 403) {
          error.message = '权限不足，无法访问';
        }
        ElementUI.Message({
          message: error.message,
          type: 'error',
          duration: 3 * 1000
        })
        return Promise.reject(error)
      }
)